<template>
  <div class="user-content">
    <div class="user-header">
      <div class="search">
        <div class="search-user">
          商品名称：<el-input v-model="data.shoppingName" style="width: 240px;height: 30px;" placeholder="请输入商品昵称" />
        </div>
        <div class="search-type">
          时间：<el-date-picker v-model="data.time" type="datetimerange" range-separator="To" start-placeholder="起始时间"
            end-placeholder="结束时间" />
        </div>
      </div>
      <div class="header-btn">
        <div class="search-btn" @click="search"><el-button type="primary"><el-icon>
              <Search />
            </el-icon>搜索</el-button></div>
        <div class="removals-btn" @click="clear"><el-button type="success"><el-icon>
              <CloseBold />
            </el-icon>重置</el-button></div>
      </div>
    </div>
    <div class="table-content">
      <div class="echarts-box">
        <VChart class="chart" :option="option" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, reactive, ref, watchEffect } from "vue";
// import * as echarts from "echarts";
import { ShowCountList, GetOrderFromOrderId, SerachShoppingCount } from '../../api/order.js'
import convertISOToCustomFormat from '../../untils/convertTime.js'
import VChart, { THEME_KEY } from "vue-echarts";

// const time = ref();
// const shoppingName = ref('');

const data = reactive({
  order: [], //被修改过后的数据
  result: [],
  allOrder: [], //未被修改后的数据
  shoppingName: '',
  searchName: [],
  countList: [],
  time: [],
  searchTime: [],
  searchAll:[]
});

const option = computed(() => {
  return {
    title: {
      text: "销售统计",
    },
    tooltip: {},
    legend: {
      // data: ["销量"],
    },
    xAxis: {
      // type: 'value',
      name: '时间',
      interval: 24 * 60 * 60 * 1000,
      data: data.order.map(item => item[0])
    },
    yAxis: {
      name: '销售量/销售金额',
    },
    dataZoom: [
      {},
      {
        type: "inside",
      },
    ],
    series: [
      {
        name: "销量",
        // type: "bar",
        type: "line",
        smooth: true,
        data: data.order
      },
      {
      name: "销量金额",
      
      data: data.order.map(item=>item[2]),
      type: 'line'
    }
    ],
  }
})

console.log(option.value);


onMounted(async () => {
  await fetchAndProcessData();
});

async function fetchAndProcessData() {
  const response = await ShowCountList();
  if (response.msgType == 8000) {
    console.log(response.data);
    for (const item of response.data) {
      const orderResponse = await GetOrderFromOrderId({ order_id: item.order_id });
      data.allOrder.push(orderResponse.data)
      console.log(orderResponse);
      processOrders(orderResponse.data);
    }
  }
}

// 处理销售数据
function processOrders(orders) {
  console.log(orders);
  orders.forEach((order) => {
    const formattedTime = convertISOToCustomFormat(order.created_at);
    const quantity = order.quantity;
    const subtotal_price=order.subtotal_price
    // console.log(formattedTime);
    // 查找是否已存在相同时间戳的数据
    // console.log(data.order);
    const existingIndex = data.order.findIndex((item) => item[0] === formattedTime);
    // console.log(existingIndex);
    if (existingIndex !== -1) {
      // 如果存在，累加销售量
      data.order[existingIndex][1] += quantity;
      data.order[existingIndex][2] += subtotal_price;
      // subtotal_price
    } else {
      // 如果不存在，添加新数据
      data.order.push([formattedTime, quantity,subtotal_price]);
    }
  });
}

// 处理销售金额





// 搜索,不是再后端，直接拿着给出的数据去判断
const search = async () => {
  // str.trim(); 去除前后文字空格
  // console.log(data.shoppingName);
  // console.log(data.allOrder);
  // console.log(convertISOToCustomFormat(data.time[0]));

  if (data.shoppingName !== '' && !data.time.length) {
    // console.log(1);
    data.order = []
    data.searchName = []
    data.searchAll=[]
    for (const item of data.allOrder) {
      for (const res of item) {
        if (res.product_name.trim() === data.shoppingName.trim()) {
          data.searchName.push(res)
        }
      }
    }
    processOrders(data.searchName);
  } else if (!!data.time.length && data.shoppingName == '') {
    // console.log(2);
    // console.log(data.time);
    data.order = []
    data.searchName = []
    data.searchAll=[]
    for (const item of data.allOrder) {
      for (const res of item) {
        if (convertISOToCustomFormat(res.created_at) >= convertISOToCustomFormat(data.time[0]) &&
          convertISOToCustomFormat(res.created_at) <= convertISOToCustomFormat(data.time[1])) {
          // data.searchName.push(res)
          // console.log(convertISOToCustomFormat(res.created_at));
          // console.log(res);
          data.searchTime.push(res)
        }
      }
    }
    processOrders(data.searchTime)
  } else if (data.shoppingName !== '' && !!data.time.length) {
    data.order = []
    data.searchName = []
    data.searchAll=[]
    // console.log(3);
    for (const item of data.allOrder) {
      for (const res of item) {
        if (res.product_name.trim() === data.shoppingName.trim()) {
          if (convertISOToCustomFormat(res.created_at) >= convertISOToCustomFormat(data.time[0]) &&
            convertISOToCustomFormat(res.created_at) <= convertISOToCustomFormat(data.time[1])) {
              data.searchAll.push(res)
          }
        }
      }
    }
    processOrders(data.searchAll)
  }else{
    data.order = []
    data.searchName = []
    data.searchAll=[]
    fetchAndProcessData();
    // console.log(1);
  }




}
console.log(data.order);

// 清除
// 
const clear = () => {
  data.shoppingName = []
  data.time = []
}

</script>


<style scoped>
.chart {
  height: 400px;
}
</style>

<style lang="less" scoped>
.user-content {
  padding: 10px;
  border: 1px solid #e0dbdb;
  border-radius: 5px;
  /* 圆角 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
  /* 好看的阴影效果 */
  margin: 10px;
  width: 100%;
}

.user-header {
  height: 50px;
  // border: 1px solid red;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;

  .search,
  .search-user,
  .search-type {
    margin-right: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .header-btn {
    display: flex;

    .search-btn {
      margin-right: 20px;
    }
  }
}

.user-middle-btn {
  margin: 10px 0px 10px 10px;
}

.demoDiv {
  margin-top: 100px;
}
</style>